#!/bin/bash

# 确保脚本遇到错误时停止执行
set -e

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        echo "错误: $1 未安装"
        exit 1
    fi
}

# 检查依赖
check_command unzip
check_command pm2

# 配置变量
MD_DIR="/home/md/Markdown"
WEB_APP_NAME="md-web"
WEB_APP_SCRIPT="./.output/server/index.mjs"
WEB_APP_INSTANCES=1

SERVER_APP_NAME="md-server"
SERVER_APP_SCRIPT="java"
SERVER_JAR="md-1.0-SNAPSHOT.jar"
SERVER_MEMORY="512m"

# 文件名变量，web 必须叫 pm2.config.js，不能改
WEB_CONFIG_FILE="pm2.config.js"
SERVER_CONFIG_FILE="pm2.server.json"

# 清理旧文件
echo "正在清理旧文件..."
rm -rf ./.output ./log
mkdir -p ./.output ./log

# 解压文件
echo "正在解压输出文件..."
unzip -q ./.output.zip -d ./ || { echo "解压失败，请检查.output.zip文件"; exit 1; }


WEB_APP_PORT="8100"
SERVER_IP="md-api.helloyt.cn"
SERVER_PORT="9999"
PROXY_PORT=$SERVER_PORT

# 解析命令行参数
for arg in "$@"; do
    case $arg in
        -server_ip=*)
            SERVER_IP="${arg#*=}"
            ;;
        -server_port=*)
            SERVER_PORT="${arg#*=}"
            ;;
        -web_port=*)
            WEB_APP_PORT="${arg#*=}"
            ;;
        -proxy_port=*)
            PROXY_PORT="${arg#*=}"
            ;;
        *)
            echo "未知参数: $arg"
            exit 1
            ;;
    esac
done

# 输出接收到的参数
echo "接收到的参数:"
echo "WEB_APP_PORT: $WEB_APP_PORT"
echo "SERVER_IP: $SERVER_IP"
echo "SERVER_PORT: $SERVER_PORT"
echo "PROXY_PORT: $PROXY_PORT"

CONFIG=$(cat << EOF
{   
    "env": "prod",
    "server": {
        "prod": {
            "ip": "$SERVER_IP",
            "port": "$PROXY_PORT"
        }
    }
}
EOF
)
CONFIG_FILE="./.output/public/config.json"
echo "$CONFIG" > "$CONFIG_FILE"

# 创建pm2.web.js文件
echo "正在创建 $WEB_CONFIG_FILE..."
WEB_CONFIG=$(cat << EOF
module.exports = {
    apps: [
        {
            // 指定 pm2 启动的进程名
            name: '$WEB_APP_NAME',
            // 指定端口
            port: $WEB_APP_PORT,
            // 启动模式，设置为“集群”。默认是 fork
            exec_mode: 'cluster',
            // 启动实例数
            instances: '$WEB_APP_INSTANCES',
            // 打包的项目文件
            script: '$WEB_APP_SCRIPT'
        }
    ]
}
EOF
)

echo "$WEB_CONFIG" > "$WEB_CONFIG_FILE"

# 创建pm2.server.json文件
echo "正在创建 $SERVER_CONFIG_FILE..."
SERVER_CONFIG=$(cat << EOF
{
  "apps": {
    "name": "$SERVER_APP_NAME",
    "script": "$SERVER_APP_SCRIPT",
    "error_file": "./log/err.log", 
    "out_file": "./log/out.log", 
    "log_date_format": "YYYY/MM/DD HH:mm:ss",
    "args": [
      "-jar",
      "-Xmx${SERVER_MEMORY}",
      "$SERVER_JAR",
      "-md_dir=$MD_DIR",
      "-port=$SERVER_PORT"
    ]
  }
}
EOF
)

echo "$SERVER_CONFIG" > "$SERVER_CONFIG_FILE"

# 启动应用
echo "正在通过PM2启动应用..."
pm2 start "$WEB_CONFIG_FILE"
pm2 start "$SERVER_CONFIG_FILE"

echo "部署完成!"    